<template>
  <ScaleBox :width="1920" :height="1080" bgc="transparent" :delay="100">
    <div class="dashboard-container">
      <!-- 页面标题、筛选区域和数据概览 -->
      <el-card class="page-header">
        <div class="header-layout">
          <div class="header-left">
            <div class="page-title">
              <el-icon>
                <Monitor />
              </el-icon>
              {{ $t('summary.jiankong') }}
            </div>
            <div class="page-subtitle">{{ $t('summary.miaoshu') }}</div>
          </div>
          <div class="header-right">
            <div class="header-stats">
              <div class="stats-card total">
                <el-icon class="icon">
                  <DataLine />
                </el-icon>
                <div class="stats-label">{{ $t('ems.totalsEquipment') }}</div>
                <div class="stats-value">{{ totalDevices }}</div>
              </div>
              <div class="stats-card power-on">
                <el-icon class="icon">
                  <SwitchButton />
                </el-icon>
                <div class="stats-label">{{ $t('summary.kaiji') }}</div>
                <div class="stats-value">{{ powerOnDevices }}</div>
              </div>
              <div class="stats-card production">
                <el-icon class="icon">
                  <Operation />
                </el-icon>
                <div class="stats-label">{{ $t('summary.shengc') }}</div>
                <div class="stats-value">{{ productionDevices }}</div>
              </div>
              <div class="stats-card standby">
                <el-icon class="icon">
                  <Timer />
                </el-icon>
                <div class="stats-label">{{ $t('summary.tingji') }}</div>
                <div class="stats-value">{{ standbyDevices }}</div>
              </div>
              <div class="stats-card error">
                <el-icon class="icon">
                  <Warning />
                </el-icon>
                <div class="stats-label">{{ $t('summary.guzhang') }}</div>
                <div class="stats-value">{{ errorDevices }}</div>
              </div>
              <div class="stats-card running">
                <el-icon class="icon">
                  <VideoPlay />
                </el-icon>
                <div class="stats-label">{{ $t('summary.yunxing') }}</div>
                <div class="stats-value">{{ runningDevices }}</div>
              </div>
            </div>


          </div>
        </div>
      </el-card>

      <!-- 图表区域 -->
      <!-- 工序分布图表 -->
      <el-row :gutter="5">
        <el-col :span="12">
          <el-card class="chart-container">
            <div class="chart-title">
              <div class="title-with-icon">
                <el-icon><PieChart /></el-icon>
                <span>{{ $t('summary.gongxu') }}</span>
              </div>
              <el-tag type="success">{{ $t('summary.shebeqty') }}</el-tag>
            </div>
            <div id="processChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-container">
            <div class="chart-title">
              <div class="title-with-icon">
                <el-icon><TrendCharts /></el-icon>
                <span>{{ $t('common.Ratio') }}</span>
              </div>
<!--              <el-radio-group v-model="trendTimeRange" size="small" @change="updateTrendChart">-->
<!--                <el-radio-button label="day">{{ $t('common.day') }}</el-radio-button>-->
<!--                <el-radio-button label="week">{{ $t('common.week') }}</el-radio-button>-->
<!--                <el-radio-button label="month">{{ $t('common.month') }}</el-radio-button>-->
<!--              </el-radio-group>-->
            </div>
            <div id="trendChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 产线运行时长 -->
      <el-row :gutter="5">
        <el-col :span="24">
          <el-card class="chart-container">
            <div class="chart-title">
              <div class="title-with-icon">
                <el-icon><Histogram /></el-icon>
                <span>{{ $t('summary.shchang') }}</span>
              </div>
              <div class="chart-actions">
                <!--<el-tag type="primary">运行时长</el-tag>-->
                <el-form :inline="true" :model="filterForm" class="filter-form">
                  <el-form-item :label="$t('wms.dates')">
                    <el-date-picker v-model="filterForm.dateRange" type="daterange"
                                    range-separator="-"
                                    :start-placeholder="$t('wms.startTime')"
                                    :end-placeholder="$t('wms.endTime')"value-format="YYYY-MM-DD" :shortcuts="dateShortcuts"
                      @change="handleDateRangeChange" />
                  </el-form-item>
                  <div class="filter-actions">
                    <el-button type="primary" @click="handleFilter">
                      <el-icon>
                        <Search />
                      </el-icon>
                      {{ $t('wms.search') }}
                    </el-button>
                    <el-button @click="resetFilter">
                      <el-icon>
                        <Refresh />
                      </el-icon>
                      {{ $t('agv.reset') }}
                    </el-button>
                    <el-button type="primary" @click="openDialog">
                      <el-icon>
                        <List />
                      </el-icon>
                      {{ $t('summary.shebeLB') }}
                    </el-button>
                  </div>
                </el-form>
              </div>
            </div>
            <div id="efficiencyChart" style="width: 100%; height: 200px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 设备列表弹框 -->
      <el-dialog v-model="dialogVisible" :title="$t('summary.shebeiZT')" width="80%" :close-on-click-modal="false"
        :close-on-press-escape="false" class="device-dialog">
        <template #header>
          <div class="dialog-header">
            <el-icon class="header-icon"><Monitor /></el-icon>
            <span>{{ $t('summary.day') }}</span>
          </div>
        </template>
        <div class="dialog-content">
          <div class="search-section">
            <el-form :inline="true" :model="from" class="search-form">
              <el-form-item class="label" :label="$t('iot.time')">
                <el-date-picker
                  v-model="from.time"
                  type="daterange"
                  range-separator="-"
                  format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                  :start-placeholder="$t('wms.startTime')"
                  :end-placeholder="$t('wms.endTime')"
                  class="custom-date-picker"
                />
              </el-form-item>
              <el-form-item class="label" :label="$t('mes.processCode')">
                <el-select v-model="from.work" clearable :placeholder="$t('wms.pleaseSelect')">
                  <el-option
                    v-for="item in data.perationList"
                    :key="item.code"
                    :label="item.text"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="label" :label="$t('agv.productionLine')">
                <el-select v-model="from.line" clearable :placeholder="$t('wms.pleaseSelect')">
                  <el-option
                    v-for="item in data.lineList"
                    :key="item.code"
                    :label="item.text"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
              <div class="search-actions">
                <el-button type="primary" @click="getEndSerch">
                  <el-icon><Search /></el-icon>
                  {{$t('wms.search')}}
                </el-button>
              </div>
            </el-form>
          </div>

          <div class="table-section">
            <el-table
              :data="data.gridData"
              style="width: 100%"
              v-loading="loading"
              height="500"
              border
              stripe
              highlight-current-row
            >
<!--              <el-table-column prop="id" :label="$t('summary.shebeiID')" width="80" align="center"></el-table-column>-->
              <el-table-column prop="processName" :label="$t('agv.process')" width="120" align="center"></el-table-column>
              <el-table-column prop="productionLineName" :label="$t('iot.title')"  align="center"></el-table-column>
              <el-table-column prop="status" :label="$t('wms.firstStatus')"  align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)" effect="light">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="attribute1" :label="$t('summary.yunxiSC')"  align="center"></el-table-column>
<!--              <el-table-column prop="attribute2" :label="$t('summary.changl')" width="120" align="center"></el-table-column>-->
<!--              <el-table-column prop="lastModifyTime" :label="$t('summary.zuihoushij')" align="center"></el-table-column>-->
            </el-table>
          </div>

          <div class="pagination-section">
            <el-pagination
              v-model:current-page="data.currentPage"
              v-model:page-size="data.pagesize"
              :page-sizes="[20, 30, 50, 100]"
              :total="data.total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeDialog">
              <el-icon><Close /></el-icon>
              {{ $t('agv.close') }}
            </el-button>
          </span>
        </template>
      </el-dialog>

    </div>
  </ScaleBox>
</template>
<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount, reactive,watch } from 'vue'
import ScaleBox from 'vue3-scale-box'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  Monitor,
  DataLine,
  SwitchButton,
  Operation,
  Timer,
  Warning,
  VideoPlay,
  Refresh,
  Search,
  List,
  PieChart,
  TrendCharts,
  Histogram,
  Close
} from '@element-plus/icons-vue'
import moment from 'moment/moment'
import { getProcessData, fetchProcess, getRunInfo } from '@/views/ProductionLineMonitoring/ProductionLineApi'
import useI18n from '@/hooks/language'


const { t } = useI18n()
// 状态数据
const loading = ref(false)
const deviceList = ref([])
const totalDevices = ref(0)
const powerOnDevices = ref(0)
const productionDevices = ref(0)
const standbyDevices = ref(0)
const errorDevices = ref(0)
const runningDevices = ref(0)
const from = ref({
  time: [],
  work: '',
  line: ''
})
const data = reactive({
  item:{},
  currentPage: 1,
  pagesize: 10,
  total: 0,
  gridData:[],
  perationList:[],
  lineList:[],
  locationList:[]
})
// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 图表实例
let processChart = null
let efficiencyChart = null
let trendChart = null
let resizeObserver = null
let autoHoverTimer = null
let currentHoverIndex = 0
let isUserInteracting = false

// 筛选表单
const filterForm = reactive({
  dateRange: []
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 工序选项
const processOptions = [
  { value: 'FS', label: '粉碎' },
  { value: 'TH', label: '贴合' },
  { value: 'PE', label: 'PE膜' },
  { value: 'JKJ', label: '锯开检' },
  { value: 'YH', label: '预混' },
  { value: 'LMHH', label: '淋膜回火' },
  { value: 'JC', label: '挤出' },
  { value: 'LVT', label: 'LVT' }
]

const productionLineOptions = ref([])
const trendTimeRange = ref('day')
const selectedDevice = ref('')
const activeTab = ref('charts')

// 添加弹框控制变量
const dialogVisible = ref(false)

// 打开弹框
const openDialog = async () => {
  const start = moment().subtract(0, 'days').format('YYYY-MM-DD')// 本月一号
  const end = moment().format('YYYY-MM-DD') // 今天
  from.value.time = [start, end]
  // 暂停自动hover
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
    autoHoverTimer = null
  }

  // 清除图表的tooltip和高亮
  if (processChart) {
    processChart.dispatchAction({
      type: 'hideTip'
    })
    processChart.dispatchAction({
      type: 'downplay',
      seriesIndex: 0
    })
  }

  await getRuleList('1')
  await getRuleList('2')
  await getList()
  dialogVisible.value = true
}

// 关闭弹框
const closeDialog = () => {
  from.value.time =[]
  from.value.work = ''
  from.value.line = ''
  dialogVisible.value = false
  // 恢复自动hover
  startAutoHover()
}

// 初始化图表
const initChart = (chartInstance, domId) => {
  if (!chartInstance) {
    const dom = document.getElementById(domId)
    if (dom) {
      chartInstance = echarts.init(dom)
      // 创建ResizeObserver
      resizeObserver = new ResizeObserver(debounce(() => {
        chartInstance.resize()
      }, 100))
      resizeObserver.observe(dom)
    }
  }
  return chartInstance
}

// 初始化所有图表
const initCharts = () => {
  const trendChartDom = document.getElementById('trendChart')
  const efficiencyChartDom = document.getElementById('efficiencyChart')
  const processChartDom = document.getElementById('processChart')

  if (trendChartDom && !trendChart) {
    trendChart = initChart(trendChart, 'trendChart')
  }

  if (efficiencyChartDom && !efficiencyChart) {
    efficiencyChart = initChart(efficiencyChart, 'efficiencyChart')
  }

  if (processChartDom && !processChart) {
    processChart = initChart(processChart, 'processChart')
  }
}

// 更新效率图表
const updateEfficiencyChart = async (devices) => {
  if (!efficiencyChart) {
    const efficiencyChartDom = document.getElementById('efficiencyChart')
    if (efficiencyChartDom) {
      efficiencyChart = echarts.init(efficiencyChartDom)
    } else {
      return
    }
  }

 let efficiencyData = devices?.map((item) => {
    const match = item.lineCode.match(/Line(\d+)/);
    const lineNumber = match ? match[1].padStart(2, "0") : "00";
    return {
      value: Number(item.timeStr),
      name: item.lineCode,
    };
  });

  const option = {
    title: {
      // text: '产线运行效率',
      left: 'center',
      top: 20
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} h'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '5%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: efficiencyData.map(d => d.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: `${t('common.RunTime')}(h)`
    },
    series: [
      {
        name: t('common.RunTime'),
        type: 'bar',
        data: efficiencyData.map(d => d.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [8, 8, 0, 0],
          borderWidth: 0
        },
        barWidth: '60%',
        label: {
          show: true,
          position: 'top',
          formatter: '{c} h',
          color: '#333',
          fontSize: 12
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        }
      }
    ]
  }

  efficiencyChart.setOption(option)
}

// 重新渲染效率图表
const reRenderEfficiencyChart = async () => {
  if (efficiencyChart) {
    efficiencyChart.dispose()
    efficiencyChart = null
  }
  await nextTick()
  const efficiencyChartDom = document.getElementById('efficiencyChart')
  if (efficiencyChartDom) {
    efficiencyChart = echarts.init(efficiencyChartDom)
    await updateEfficiencyChart(deviceList.value)
  }
}

// 日期范围处理
const handleDateRangeChange = (val) => {
  if (val) {
    filterForm.startDate = val[0]
    filterForm.endDate = val[1]
  } else {
    filterForm.startDate = ''
    filterForm.endDate = ''
  }
}

// 筛选处理
const handleFilter = () => {
  getData()
}

const resetFilter =async () => {
  filterForm.dateRange = []
  await getData()
}
// 默认当天时间
const getToday = () => {
  const start = moment().subtract(0, 'days').format('YYYY-MM-DD')// 本月一号
  const end = moment().format('YYYY-MM-DD') // 今天
  filterForm.dateRange = [start, end]
}
// 获取设备数据
const getData = async () => {
  const res = await getRunInfo({
    beginTime: filterForm.dateRange?.[0] && filterForm.dateRange?.[0]
      ? moment(filterForm.dateRange?.[0]).format('YYYY-MM-DD 00:00:00')
      : '',
    endTime: filterForm.dateRange?.[1] && filterForm.dateRange?.[1]
      ? moment(filterForm.dateRange?.[1]).format('YYYY-MM-DD 23:59:59')
      : '',
  })
  if (res.code === 200) {
    totalDevices.value = res.result.total  //设备总数
    res.result.totalCounts.map(item => {
      if (item.status == '开机') {
        powerOnDevices.value  = item.count
      }
      if (item.status == '生产') {
        productionDevices.value = item.count
      }
      if (item.status == '停机') {
        standbyDevices.value = item.count
      }
      if (item.status == '故障') {
        errorDevices.value = item.count
      }
      if (item.status == '运行') {
        runningDevices.value = item.count
      }
    })
    updateEfficiencyChart(res.result.runTimes)
  }
};
// 获取数据
const fetchData = async (params = {}) => {
  loading.value = true
  try {
    // const response = await fetch('http://172.16.100.10:9000/eleltile/QYWX/message/response.json')
    // const data = await response.json()
    const  params = {
      beginTime: moment().format('YYYY-MM-DD 00:00:00'),
      endTime: moment().format('YYYY-MM-DD 23:59:59')
    }
    let data = await getRunInfo(params)

    if (data.code === 200) {
      deviceList.value = data.result.details
      // updateStatistics(data.result.sheBeiDetails)
      updateCharts(data.result.details)
      // updateProductionLineOptions(data.result.details)


      await nextTick()
      setTimeout(() => {
        initCharts()
        // updateEfficiencyChart(data.result.sheBeiDetails)
        // updateTrendChart()
        updateTrendChart2(data.result.totalPercents)
      }, 100)
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStatistics = (devices) => {
  if (!devices || !Array.isArray(devices)) {
    console.error('设备数据无效')
    return
  }



}

// 更新产线选项
const updateProductionLineOptions = (devices) => {
  const uniqueLines = [...new Set(devices.map(d => d.productionLineName))]
  productionLineOptions.value = uniqueLines.map(line => ({
    value: line,
    label: line
  }))
}

// 自动hover效果
const startAutoHover = () => {
  if (dialogVisible.value) return // 如果弹框打开，不启动自动hover

  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }

  autoHoverTimer = setInterval(() => {
    if (!isUserInteracting && processChart && processChart.getOption().series[0].data.length > 0) {
      // 先取消所有高亮
      processChart.dispatchAction({
        type: 'downplay',
        seriesIndex: 0
      })

      currentHoverIndex = (currentHoverIndex + 1) % processChart.getOption().series[0].data.length
      // 显示tooltip
      processChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: currentHoverIndex
      })
      // 高亮当前项
      processChart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: currentHoverIndex
      })
    }
  }, 2000)
}

// 处理用户交互
const handleUserInteraction = () => {
  isUserInteracting = true
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }

  // 用户停止交互后3秒重新开始自动hover
  setTimeout(() => {
    isUserInteracting = false
    startAutoHover()
  }, 3000)
}

// 更新图表
const updateCharts = async (devices) => {
  await nextTick()

  if (!processChart) {
    const processChartDom = document.getElementById('processChart')
    if (processChartDom) {
      processChart = echarts.init(processChartDom)
      // 添加图表事件监听
      processChartDom.addEventListener('mouseover', handleUserInteraction)
      processChartDom.addEventListener('mouseout', handleUserInteraction)
    }
  }

  // 工序分布图表
  const processData = {}
  const processDataMap = {
    'JC': 'Extursion',
    'JKJ':'Saw cutting',
    'DR':'Pack and wrap',
    'TH':'Gluing',
    'PE':'PE',
    'YH':'Mixing',
    'FS':'Grinding',
    'LMHH':'LMHH',
  }
  devices.forEach(device => {
    processData[device.processCode] = (processData[device.processCode] || 0) + 1
  })
  const processDataMapped = Object.entries(processData).map(([key, value]) => {
    const name = processDataMap[key] || key; // 使用映射关系，如果没有则保留原始 key
    return { name, value };
  });

  if (processChart) {
    processChart.setOption({
      title: {
        left: 'center',
        top: 20
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle'
      },
      series: [
        {
          name: t('summary.gongxufenb'),
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['60%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)',
            fontSize: 14,
            fontWeight: 'bold',
            color: '#333'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: processDataMapped,
          labelLine: {
            show: true
          }
        },
        {
          name: t('wms.totals'),
          type: 'pie',
          radius: ['0%', '0%'],
          center: ['60%', '50%'],
          label: {
            position: 'center',
            formatter: `${t('wms.totals')}: ${totalDevices.value}`,
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          },
          data: [1]
        }
      ]
    })
    startAutoHover()
  }
}

// 状态处理函数
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'info'    // 开机
    case 2: return 'success' // 生产
    case 3: return 'warning' // 停机
    case 4: return 'danger'  // 故障
    case 5: return 'primary' // 运行
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '开机'
    case 2: return '生产'
    case 3: return '停机'
    case 4: return '故障'
    case 5: return '运行'
    default: return '未知'
  }
}
// 更新趋势图表
const updateTrendChart2 = async (totalPercents) => {
  if (!trendChart) return;
  const processData =totalPercents
  // 工序列表和对应的开机率数据
  // const processData = [
  //   { name: '粉碎', rate: 99.5 },
  //   { name: '贴合', rate: 97.2 },
  //   { name: 'PE膜', rate: 94.8 },
  //   { name: '锯开检', rate: 92.3 },
  //   { name: '预混', rate: 88.6 },
  //   { name: '淋膜回火', rate: 86.2 },
  //   { name: '挤出', rate: 82.4 },
  //   { name: 'LVT', rate: 78.9 },
  //   { name: '包装', rate: 65.5 },
  //   { name: '质检', rate: 45.2 },
  //   { name: '仓储', rate: 30.8 },
  //   { name: '运输', rate: 15.3 }
  // ];

  // 按照开机率从小到大排序
  // totalPercents.sort((a, b) => a.percent - b.percent);
  totalPercents.sort((a, b) => {
    const aPercent = parseFloat(a.percent.replace('%', '')); // 去掉 % 并转换为数字
    const bPercent = parseFloat(b.percent.replace('%', '')); // 去掉 % 并转换为数字
    return aPercent - bPercent; // 进行排序
  });

  // 分离工序名称和开机率数据
  const processes = processData.map(item => item.title);
  // const powerOnRateData = processData.map(item => item.percent);
  const powerOnRateData = processData.map(item => {
    return parseFloat(item.percent.replace('%', '')); // 去掉 % 并转换为数字，不除以 100
  });

  const option = {
    grid: {
      left: '0%',
      right: '15%',
      bottom: '5%',
      top: '5%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>{a}: {c}%',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#dcdfe6',
      borderWidth: 1,
      textStyle: {
        color: '#606266'
      },
      padding: [8, 12]
    },
    xAxis: {
      type: 'value',
      name: `${t('ems.powerRatios')}(%)`,
      nameTextStyle: {
        color: '#606266',
        fontSize: 12,
        padding: [0, 0, 0, 40]
      },
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        color: '#909399',
        fontSize: 11
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ebeef5'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: processes,
      axisLabel: {
        interval: 0,
        margin: 20,
        textStyle: {
          fontSize: 12,
          color: '#606266',
          fontWeight: 500
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: t('ems.powerRatios'),
        type: 'bar',
        data: powerOnRateData,
        barWidth: '60%',
        itemStyle: {
          color: function(params) {
            const value = params.value;
            if (value >= 98) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#13CE66' }, // 极好
                { offset: 1, color: '#85E2B8' }
              ]);
            } else if (value >= 95) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#67C23A' }, // 优秀
                { offset: 1, color: '#95D475' }
              ]);
            } else if (value >= 80) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#E6A23C' }, // 良好
                { offset: 1, color: '#F3D19E' }
              ]);
            } else if (value >= 60) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#F7BA2A' }, // 一般
                { offset: 1, color: '#F9D566' }
              ]);
            } else if (value >= 40) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#FF9800' }, // 需关注
                { offset: 1, color: '#FFB74D' }
              ]);
            } else if (value >= 20) {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#F56C6C' }, // 严重警告
                { offset: 1, color: '#FAB6B6' }
              ]);
            } else {
              return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#9E9E9E' }, // 异常
                { offset: 1, color: '#BDBDBD' }
              ]);
            }
          },
          borderRadius: [0, 8, 8, 0],
          shadowColor: 'rgba(0, 0, 0, 0.1)',
          shadowBlur: 4,
          shadowOffsetY: 2
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%',
          textStyle: {
            color: '#606266',
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Arial, sans-serif'
          },
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          padding: [4, 8],
          borderRadius: 4,
          borderColor: '#dcdfe6',
          borderWidth: 1
        },
        emphasis: {
          itemStyle: {
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 8,
            shadowOffsetY: 4
          }
        }
      }
    ],
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  };

  trendChart.setOption(option);
};

// 更新趋势图表
const updateTrendChart = async () => {
  if (!trendChart) return

  // 根据时间范围生成数据
  let dates = []
  let dataLength = 0
  switch (trendTimeRange.value) {
    case 'day':
      dates = Array.from({ length: 24 }, (_, i) => `${i}:00`)
      dataLength = 24
      break
    case 'week':
      dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      dataLength = 7
      break
    case 'month':
      dates = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
      dataLength = 30
      break
  }

  const statusData = {
    '开机': Array.from({ length: dataLength }, () => Math.floor(Math.random() * 10)),
    '生产': Array.from({ length: dataLength }, () => Math.floor(Math.random() * 10)),
    '停机': Array.from({ length: dataLength }, () => Math.floor(Math.random() * 10)),
    '故障': Array.from({ length: dataLength }, () => Math.floor(Math.random() * 5)),
    '运行': Array.from({ length: dataLength }, () => Math.floor(Math.random() * 10))
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: Object.keys(statusData),
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '100px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '设备数量'
    },
    series: Object.entries(statusData).map(([name, data]) => ({
      name,
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data
    }))
  }

  trendChart.setOption(option)
}
// 获取工序 产线 位置列表
const getRuleList = (type) => {
  if (type === '1') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      data.perationList = res.result.list
    })
  } else if (type === '2') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      data.lineList = res.result?.list?.filter(item => item.code.includes('PD'));
    })
  } else if (type === '3') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      data.locationList = res.result.list
    })
  }
}
// 获取弹窗数据
const getList =async () =>{
  try {
    loading.value = true
    const  params = {
      processCode: from.value.work,
      lineCode: from.value.line,
      current: data.currentPage,
      size: data.pagesize,
      beginTime: from.value?.time && from.value.time[0]
        ? moment(from.value.time[0]).format('YYYY-MM-DD')
        : '',
      endTime: from.value?.time && from.value.time[1]
        ? moment(from.value.time[1]).format('YYYY-MM-DD')
        : '',
    }
    let res = await getProcessData(params)
    if(res.code == 200){
      data.gridData = res.result.sheBeiDetails
      data.total = res.result.total
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}
// 分页
const handleSizeChange = (val) => {
  data.pagesize = val
  getList()
}
const handleCurrentChange = (val) => {
  data.currentPage = val
  getList()
}
// 搜索
const getEndSerch = () => {
  data.currentPage = 1
  getList()
}
const refreshData = () => {
  getList()
}
// 组件卸载前清理
onBeforeUnmount(() => {
  if (processChart) {
    try {
      processChart.$el.removeEventListener('mouseover', handleUserInteraction)
      processChart.$el.removeEventListener('mouseout', handleUserInteraction)
    }catch (e) {
      console.error("removeEventListener 报错了" );
      return ;
    }
    processChart.dispose()
    processChart = null
  }
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }
  if (efficiencyChart) {
    efficiencyChart.dispose()
    efficiencyChart = null
  }
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
})

onMounted(async () => {
  await getToday()
  await getData()
  await fetchData()
})
</script>

<style scoped lang="scss">
:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --background-color: #f5f7fa;
}

.dashboard-container {
  padding: 20px;
  background: var(--background-color);
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 5px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-layout {
  display: flex;
  gap: 20px;
  min-height: 70px;
  position: relative;
}

.header-layout::after {
  content: '';
  position: absolute;
  left: 300px;
  top: 10%;
  bottom: 10%;
  width: 1px;
  background: linear-gradient(to bottom, transparent, #DCDFE6, transparent);
}

.header-left {
  flex: 0 0 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
  z-index: 1;
}

.header-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: relative;
  z-index: 1;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.page-title .el-icon {
  margin-right: 10px;
  font-size: 28px;
  color: var(--primary-color);
}

.page-subtitle {
  color: #909399;
  font-size: 14px;
}

.header-stats {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
}

.stats-card {
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  border: 1px solid #EBEEF5;
}

.stats-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.stats-card.total {
  background: linear-gradient(135deg, #409EFF 0%, #a0cfff 100%);
}

.stats-card.power-on {
  background: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
}

.stats-card.production {
  background: linear-gradient(135deg, #67C23A 0%, #b3e19d 100%);
}

.stats-card.standby {
  background: linear-gradient(135deg, #E6A23C 0%, #f3d19e 100%);
}

.stats-card.error {
  background: linear-gradient(135deg, #F56C6C 0%, #fab6b6 100%);
}

.stats-card.running {
  background: linear-gradient(135deg, #409EFF 0%, #a0cfff 100%);
}

.stats-card .icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.8;
  transition: all 0.3s ease;
  color: #ffffff;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.stats-card:hover .icon {
  opacity: 1;
  transform: translateY(-50%) scale(1.1);
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));
}

.stats-card .stats-label {
  color: #ffffff;
  font-size: 14px;
  margin-bottom: 8px;
  font-weight: 500;
}

.stats-card .stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #ffffff;
  margin: 0;
}

.filter-form {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-bottom: 20px;
  // border-bottom: 1px solid #EBEEF5;
  gap: 20px;

  .el-form-item {
    margin-bottom: 0;
    display: flex;
    align-items: center;
  }

  .el-date-picker {
    width: 360px;
  }

  .filter-actions {
    display: flex;
    align-items: center;
    gap: 2px;
  }
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  height: 440px;
  position: relative;
  transition: all 0.3s;
  overflow: hidden;
}

.chart-container .chart {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20px;
  width: 100%;
  height: 100%;
}

#processChart,
#trendChart,
#efficiencyChart {
  width: 100%;
  height: 100%;
  min-height: 338px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-title .el-tag {
  margin-left: 10px;
}

.analysis-section {
  margin-top: 20px;
}

.analysis-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  transition: all 0.3s;
}

.analysis-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.analysis-header {
  padding: 15px 20px;
  // border-bottom: 1px solid #EBEEF5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.analysis-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.analysis-content {
  padding: 20px;
}

.status-timeline {
  height: 300px;
}

.device-list {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-badge {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-running {
  background-color: var(--success-color);
  color: white;
}

.status-warning {
  background-color: var(--warning-color);
  color: white;
}

.status-error {
  background-color: var(--danger-color);
  color: white;
}

.el-card {
  margin-bottom: 5px;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  box-sizing: border-box;
}

.el-card__body {
  padding: 20px;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 10px;

  .filter-form {
    margin: 0;
    padding: 0;
    display: flex;
    align-items: center;
    gap: 10px;

    .el-form-item {
      margin-bottom: 0;
    }

    .el-date-picker {
      width: 300px;
    }

    .filter-actions {
      display: flex;
      gap: 5px;
    }
  }
}

.chart-actions .el-button {
  margin-left: 10px;
}

.chart-actions .el-icon {
  margin-right: 4px;
}

.charts-card {
  margin-top: 20px;
}

.device-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-dialog__header) {
    padding: 16px 20px;
    margin: 0;
    border-bottom: 1px solid #EBEEF5;
    background-color: #f5f7fa;
  }

  :deep(.el-dialog__title) {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  .dialog-content {
    padding: 20px;
  }

  .search-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #EBEEF5;

    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      align-items: center;

      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }

      .label {
        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #606266;
          padding-right: 8px;
        }
      }

      .custom-date-picker {
        width: 240px;
      }

      .el-select {
        width: 200px;
      }

      .search-actions {
        display: flex;
        gap: 8px;
        margin-left: auto;

        .el-button {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 8px 15px;
        }
      }
    }
  }

  .table-section {
    margin-bottom: 20px;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    :deep(.el-table) {
      border-radius: 4px;

      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
      }

      .el-table__row {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .pagination-section {
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }

  .dialog-footer {
    padding: 10px 20px;
    border-top: 1px solid #EBEEF5;
    display: flex;
    justify-content: flex-end;
  }
}

.title-with-icon {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    font-size: 18px;
    color: var(--el-color-primary);
  }

  span {
    font-size: 16px;
    font-weight: bold;
  }
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;

  .header-icon {
    font-size: 18px;
    color: var(--el-color-primary);
  }

  span {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}
</style>
